package com.hjxr.quota.define.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjxr.common.utils.StringUtils;
import com.hjxr.quota.datasource.domain.*;
import com.hjxr.quota.datasource.mapper.*;
import com.hjxr.quota.define.domain.*;
import com.hjxr.quota.define.dto.QuotaValueVo;
import com.hjxr.quota.define.mapper.*;
import com.hjxr.quota.define.service.QuotaValueService;
import com.hjxr.quota.tool.query.BaseQueryTool;
import com.hjxr.quota.tool.query.QueryToolFactory;
import com.hjxr.quota.util.JdbcUtils;
import com.hjxr.quota.util.PageUtil;
import com.hjxr.quota.util.Query;
import com.hjxr.quota.datasource.domain.*;
import com.hjxr.quota.datasource.mapper.*;
import com.hjxr.quota.define.domain.*;
import com.hjxr.quota.define.mapper.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ma
 * @version v1.0
 * @date 2020/9/17
 **/
@Service
public class QuotaValueServiceImpl extends ServiceImpl<QuotaValueMapper, QuotaValue> implements QuotaValueService {

    @Resource
    private QuotaSourceMapper quotaSourceMapper;
    @Resource
    private DimRelationMapper dimRelationMapper;  //dimension_relation
    @Resource
    private ColnameAliasMapper colnameAliasMapper;
    @Resource
    private QuotaDimensionMapper quotaDimensionMapper;
    @Resource
    private QuotaValueMapper quotaValueMapper;
    @Resource
    private QuotaMapper quotaMapper;
    @Resource
    private TablenameAliasMapper tablenameAliasMapper;  //tablename_alias
    @Resource
    private JobDatasourceMapper jobDatasourceMapper;
    @Resource
    QuotaDimensionDetailMapper quotaDimensionDetailMapper;
    @Resource
    QuotaDimRelationDetailMapper quotaDimRelationDetailMapper;
    @Resource
    QuotaDimensionRelationMapper quotaDimensionRelationMapper;

    @Override
    public Boolean insert(Integer quotaId, String measure) {
        //计算指标值
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<QuotaSource> quotaWrapper = new QueryWrapper<>();
        quotaWrapper.eq("QUOTA_ID" , quotaId);
        QuotaSource quotaSource = quotaSourceMapper.selectOne(quotaWrapper);//根据指标id查询到指标来源表数据
        if (quotaSource != null) {
            if ("1".equals(quotaSource.getSType())) {//以数据库方式建立
                QueryWrapper<DimRelation> dimRelationWrapper = new QueryWrapper<>();
                dimRelationWrapper.eq("QUOTA_ID" , quotaId);
                List<DimRelation> dimRelationList = dimRelationMapper.selectList(dimRelationWrapper);//根据指标id查询到维度与指标关系表数据
                if (dimRelationList.size() == 0) {//未查寻到结果
                    return false;
                }
                //获取查询指标值where条件参数
                for (DimRelation dimRelation : dimRelationList) {
                    // Integer dimId = dimRelation.getDimensionId();//根据指标id获得维度id
                    Integer dimId = 0;
                    String name = colnameAliasMapper.queryName(dimId);//维度对应字段名
                    QuotaDimension quotaDimension = quotaDimensionMapper.selectById(dimId);//根据维度id获得维度名称
                    if (quotaDimension == null) {
                        return false;
                    }
                    map.put(name, quotaDimension.getDimensionName());
                }
                List<Float> valueList = quotaValueMapper.computeValueF(map, quotaSource.getSTable(), quotaSource.getSCol());
                QuotaValue quotaValue = new QuotaValue();
                if (valueList.size() == 1) {
                    //只有一条值
                    quotaValue.setValue(valueList.get(0));
                } else if (valueList.size() == 0) {
                    //无此指标值  不做处理为空
                } else {
                    //有多条值
                    float sum = 0;
                    for (Float num : valueList) {
                        sum = sum + num;
                    }
                    quotaValue.setValue(sum);
                }
                quotaValue.setQuotaId(quotaId);
                quotaValue.setDimensions(quotaSource.getDimensions());
                quotaValue.setValue(valueList.get(0));
                Quota quota = quotaMapper.selectById(quotaId);
                if (quota != null) {
                    quotaValue.setCode(quota.getCode());
                }
                return save(quotaValue);
            }
        }
        //该指标id不存在指标来源
        return false;
    }

    @Override
    public Boolean updateValue(QuotaValue quotaValue) {
        int i = quotaValueMapper.updateById(quotaValue);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Boolean addQuotaValue(Integer tablenameAliasId) throws Exception {
        Date now = new Date();
        // 根据数据表别名Id获取数据表对象，不存在则返回失败
        TablenameAlias table = tablenameAliasMapper.selectById(tablenameAliasId);
        if (table == null)
            return false;
        // 根据数据表id获取对应的所有字段别名对象
        List<ColnameAlias> col_list = colnameAliasMapper.selectByTablenameAliasId(tablenameAliasId);

        if (col_list.size() == 0)
            return false;

        // 维度集合, {columnName: colnameAliasId}
        Map<String, Integer> dimMap = new HashMap<>();
        // 指标集合, {columnName: colnameAliasId}
        Map<String, Integer> qtMap = new HashMap<>();

        col_list.forEach(col -> {
            if ("1".equals(col.getIsdimension()))
                dimMap.put(col.getColumnName(), col.getId());
            if ("1".equals(col.getIsquota()))
                qtMap.put(col.getColumnName(), col.getId());
        });

        if (dimMap.size() == 0 || qtMap.size() == 0)
            return false;

        JobDatasource datasource = jobDatasourceMapper.selectById(table.getDatasourceId());
        BaseQueryTool queryTool = QueryToolFactory.getByDbType(datasource);
        Connection connection = queryTool.getConnection();
        String dimStr = String.join("," , dimMap.keySet());

        //循环指标，配合维度生成指标值
        for (String qt : qtMap.keySet()) {
            QueryWrapper<QuotaSource> wrapper = new QueryWrapper<>();
            wrapper.eq("COLNAME_ID" , qtMap.get(qt)); //根据字段别名查询指标来源记录
            // 根据字段别名获取指标来源表记录
            QuotaSource quotaSource = quotaSourceMapper.selectOne(wrapper);
            // 具有维度详情的相关字段列表
            List<Integer> topList = new ArrayList<>();
            List<Integer> relList = new ArrayList<>();
            if (quotaSource != null) {
//              select bank_no, account_type, sum(amount) sm, max(amount) mx, min(amount) mn, avg（amount) av, count(amount) from BK_BANK_CHECKUP_BILL
//              GROUP by  bank_no, account_type
                String querySql = "select " + dimStr + ", " + "sum(" + qt + ") sm," +
                        " max(" + qt + ") mx, min(" + qt + ") mn, avg(" + qt + ") av, " +
                        "count(" + qt + ") ct from " + table.getTableName() + " group by " + dimStr;

                Statement stmt = null;
                ResultSet rs = null;
                try {
                    // 执行sql查询
                    stmt = connection.createStatement();
                    rs = stmt.executeQuery(querySql);
                    // 循环指标，维度s统计结果
                    while (rs.next()) {
                        String dimensions = ",";

                        for (String dn : dimMap.keySet()) {
                            String codeValue = rs.getString(dn);
//                QueryWrapper<QuotaDimensionDetail> w = new QueryWrapper<>();
//                w.eq("COLNAME_ID", dimMap.get(dn)).eq("CODE_VALUE", codeValue);

                            Map<String, Object> queryMap = new HashMap<>();
                            queryMap.put("COLNAME_ID" , dimMap.get(dn));
                            queryMap.put("CODE_VALUE" , codeValue);
                            // 根据字段别名ID和维度编码，查询维度详情表记录
                            List<QuotaDimensionDetail> qdd = quotaDimensionDetailMapper.selectByMap(queryMap);
                            if (qdd.size() != 0) {
                                // 有记录
                                Integer dimensionId = qdd.get(0).getDimensionId();
                                dimensions += dimensionId + ",";

                                QuotaDimension dim = this.getDimesionTop(dimensionId);
                                if (!topList.contains(dim.getId()))
                                    topList.add(dim.getId());

                                if (!relList.contains(dimensionId)) {
                                    // 则增加QuotaDImRelationDetail记录
                                    QuotaDimRelationDetail qdrd = new QuotaDimRelationDetail();
                                    qdrd.setDimensionId(dimensionId);
                                    qdrd.setQuotaId(quotaSource.getQuotaId());
                                    qdrd.setUpdateDate(now);
                                    qdrd.setRootDimId(dim.getId());
                                    quotaDimRelationDetailMapper.insert(qdrd);
                                    relList.add(dimensionId);
                                }


                            } else {
                                // 查找不到对应值，则直接
                                dimensions += ",";
                                break;
                            }

                        }
                        if (dimensions.contains(",,"))
                            continue;
                        QuotaValue quotaValue = new QuotaValue();
                        quotaValue.setDimensions(dimensions);
                        quotaValue.setQuotaId(quotaSource.getQuotaId());
                        quotaValue.setAv(rs.getFloat("av"));
                        quotaValue.setSm(rs.getFloat("sm"));
                        quotaValue.setValue(rs.getFloat("sm"));
                        quotaValue.setMn(rs.getFloat("mn"));
                        quotaValue.setCt(rs.getInt("ct"));
                        quotaValue.setMx(rs.getFloat("mx"));
                        quotaValue.setUpdateDate(now);
                        quotaValueMapper.insert(quotaValue);
                    }
//                    List<List<QuotaValue>> lists = fixedGrouping(list, 20);
//                    for (List<QuotaValue> quotaValues : lists) {
//                        quotaValueMapper.batchInsertValue(quotaValues);
//                    }

                    for (Integer id : topList) {
                        QuotaDimensionRelation qdr = new QuotaDimensionRelation();
                        qdr.setQuotaId(quotaSource.getQuotaId());
                        qdr.setDimensionId(id);
                        qdr.setUpdateDate(now);
                        quotaDimensionRelationMapper.insert(qdr);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println(e.getMessage());
                } finally {
                    JdbcUtils.close(rs);
                    JdbcUtils.close(stmt);
                }
                // 增加QuotaDimensionRelation
            }


        }
        return true;
    }

    public static <T> List<List<T>> fixedGrouping(List<T> source, int n) {

        if (null == source || source.size() == 0 || n <= 0)
            return null;
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;
        int size = (source.size() / n);
        for (int i = 0; i < size; i++) {
            List<T> subset = null;
            subset = source.subList(i * n, (i + 1) * n);
            result.add(subset);
        }
        if (remainder > 0) {
            List<T> subset = null;
            subset = source.subList(size * n, size * n + remainder);
            result.add(subset);
        }
        return result;
    }

    private QuotaDimension getDimesionTop(Integer id) {
        QuotaDimension dim = quotaDimensionMapper.selectById(id);
        if (null != dim && dim.getUpperId() != 0) {
            return getDimesionTop(dim.getUpperId());
        } else
            return dim;
    }


    //筛选查询指标数据
    private List<QuotaValue> getQuotaValues(List<Integer> quotaIds, List<Integer> dimensionIds, Integer limit) {
        /** 查询维度根节点进行分类 */
        QueryWrapper<QuotaDimRelationDetail> relationWrapper = new QueryWrapper<QuotaDimRelationDetail>()
                .in("QUOTA_ID" , quotaIds).in("DIMENSION_ID" , dimensionIds);
        List<QuotaDimRelationDetail> quotaDimRelationDetails = quotaDimRelationDetailMapper.selectList(relationWrapper);
        /** key->根节点id  value->关系表数据 */
        Map<Integer, List<QuotaDimRelationDetail>> quotaDimRMap = quotaDimRelationDetails.stream()
                .collect(Collectors.groupingBy(key -> key.getRootDimId()));
        /** 组装维度值查询wrapper 去掉之前的筛选方法 这里同时把维度id留出来查询维度名称*/
        QueryWrapper<QuotaValue> valueQueryWrapper = new QueryWrapper<QuotaValue>().in("QUOTA_ID" , quotaIds);
        quotaDimRMap.forEach((k, v) -> {
            valueQueryWrapper.and((obj) -> {
                for (QuotaDimRelationDetail qdrd : v) {
                    obj.or().like("DIMENSIONS" , qdrd.getDimensionId());
                }
            });
        });
        /** 查询指标值 */
        List<QuotaValue> quotaValues = new ArrayList<>();
        if (limit > 0) {
            Page<QuotaValue> page = new Page<>();
            page.setCurrent(0);
            page.setSize(limit);
            Page<QuotaValue> selectPage = this.baseMapper.selectPage(page, valueQueryWrapper);
            quotaValues = selectPage.getRecords();
        } else {
            quotaValues = this.baseMapper.selectList(valueQueryWrapper);
        }
        return quotaValues;
    }

    /**
     * 根据维度id查询维度名称 返回map结构
     */
    private Map<Integer, QuotaDimension> getDimensionNameMap(List<QuotaValue> quotaValues) {
        /** 查询维度名称  还需要知道根维度的名字...赶时间先在查一遍关系表吧...还是放在维度表好 不需要那么多条件... */
        Set<String> dimIds = Arrays.stream(quotaValues
                .stream()
                .map(QuotaValue::getDimensions)
                .collect(Collectors.joining())
                .split(",")).filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toSet());
        /** key->维度id  value->维度表数据 */
        Map<Integer, QuotaDimension> quotaDimensionMap = quotaDimensionMapper.selectBatchIds(dimIds).stream()
                .collect(Collectors.toMap(QuotaDimension::getId, a -> a, (k1, k2) -> k1));
        return quotaDimensionMap;
    }

    private String getValue(String type, QuotaValue value) {
        Float result = 0f;
        switch (type) {
            case "0":
                result = value.getValue() == null ? value.getSm() : value.getValue();
                break;
            case "1":
                result = value.getMx() == null ? 0 : value.getMx();
                break;
            case "2":
                result = value.getMn() == null ? 0 : value.getMn();
                break;
            case "3":
                result = value.getCt() == null ? 0 : value.getCt().floatValue();
                break;
            case "4":
                result = value.getAv() == null ? 0 : value.getAv();
                break;
        }
        return result + "";
    }

    @Override
    public String getReportJson(Map<String, String> param, List<Integer> dimensionIds, String type) {
        List<Map<String, String>> maps = new ArrayList<>();
        /** 预指标id筛选 */
        List<Integer> quotaIds = param.keySet().stream().map(id -> Integer.valueOf(id)).collect(Collectors.toList());
        List<QuotaValue> quotaValues = this.getQuotaValues(quotaIds, dimensionIds, 0);
        if (quotaValues != null && quotaValues.size() > 0) {
            /** 查询维度名称  还需要知道根维度的名字...赶时间先在查一遍关系表吧...还是放在维度表好 不需要那么多条件... */
            Set<String> dimIds = Arrays.stream(quotaValues
                    .stream()
                    .map(QuotaValue::getDimensions)
                    .collect(Collectors.joining(","))
                    .split(",")).filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toSet());
            QueryWrapper<QuotaDimRelationDetail> wrapper = new QueryWrapper<QuotaDimRelationDetail>()
                    .select("DISTINCT ROOT_DIM_ID,DIMENSION_ID").in("QUOTA_ID" , quotaIds).in("DIMENSION_ID" , dimIds);

            List<QuotaDimRelationDetail> relationDetails = quotaDimRelationDetailMapper.selectList(wrapper);
            dimIds.addAll(relationDetails.stream().map(item -> item.getRootDimId().toString()).collect(Collectors.toSet()));
            /** key->维度id  value->关系表数据 */
            Map<Integer, QuotaDimRelationDetail> rootMap = relationDetails.stream()
                    .collect(Collectors.toMap(QuotaDimRelationDetail::getDimensionId, a -> a, (k1, k2) -> k1));
            /** key->维度id  value->维度表数据 */
            Map<Integer, QuotaDimension> quotaDimensionMap = quotaDimensionMapper.selectBatchIds(dimIds).stream()
                    .collect(Collectors.toMap(QuotaDimension::getId, a -> a, (k1, k2) -> k1));

            Map<List<String>, Integer> matchMap = new HashMap<>();
            /** 组装前端所需格式 */
            f:
            for (QuotaValue quotaValue : quotaValues) {
                Map<String, String> map = new LinkedHashMap<>();
                List<String> ids = Arrays.stream(quotaValue.getDimensions().split(","))
                        .filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toList());
                /** 已经存在于返回值只设置值到对应的map中 */
                for (Map.Entry<List<String>, Integer> entry : matchMap.entrySet()) {
                    List<String> k = entry.getKey();
                    Integer index = entry.getValue();
                    if (k.containsAll(ids)) {
                        Map<String, String> existMap = maps.get(index);
                        existMap.put(param.get(quotaValue.getQuotaId() + ""), this.getValue(type, quotaValue));
                        continue f;
                    }
                }
                ids.forEach(id -> {
                    QuotaDimension children = quotaDimensionMap.get(Integer.valueOf(id));
                    Integer rootDimId = rootMap.get(Integer.valueOf(id)).getRootDimId();
                    QuotaDimension root = quotaDimensionMap.get(rootDimId);
                    map.put(root.getDimensionName(), children.getDimensionName());
                });
                map.put(param.get(quotaValue.getQuotaId() + ""), this.getValue(type, quotaValue));
                if (map.size() > 0) {
                    maps.add(map);
                    matchMap.put(ids, maps.size() - 1);
                }
            }
        }
        return JSON.toJSONString(maps);
    }

    @Override
    public String getScatterChartsJson(Map<String, String> param, List<Integer> dimensionIds, String type, Integer limit) {
        Map<String, Object> resultMap = new HashMap<>();
        /** 预指标id筛选 */
        List<Integer> quotaIds = param.keySet().stream().map(id -> Integer.valueOf(id)).collect(Collectors.toList());
        List<QuotaValue> quotaValues = this.getQuotaValues(quotaIds, dimensionIds, limit);
        if (null != quotaValues && quotaValues.size() > 0) {
            Map<Integer, QuotaDimension> quotaDimensionMap = this.getDimensionNameMap(quotaValues);
            /** 对指标数据按照指标id分组 */
            Map<Integer, List<QuotaValue>> quotaMap = quotaValues.stream().collect(Collectors.groupingBy(key -> key.getQuotaId()));
            /** 组装散点图需要数据 */
            Set<String> dimensions = new HashSet<>();
            quotaMap.forEach((k, v) -> {
                List<List<String>> lists = new ArrayList<>();
                for (QuotaValue value : v) {
                    List<String> list = new ArrayList<>();
                    List<String> ids = Arrays.stream(value.getDimensions().split(","))
                            .filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toList());
                    StringBuilder sb = new StringBuilder();
                    sb.append("|");
                    ids.forEach(id -> {
                        QuotaDimension children = quotaDimensionMap.get(Integer.valueOf(id));
                        sb.append(children.getDimensionName()).append("|");
                    });
                    dimensions.add(sb.toString());
                    list.add(sb.toString());
                    list.add(this.getValue(type, value));
                    lists.add(list);
                }
                resultMap.put(k.toString(), lists);
            });
            resultMap.put("xAxis" , dimensions);
        }
        return JSON.toJSONString(resultMap);
    }

    @Override
    public String getPieChartsJson(Map<String, String> param, List<Integer> dimensionIds, String type, Integer limit) {
        List<Map<String, String>> maps = new ArrayList<>();
        List<Integer> quotaIds = param.keySet().stream().map(id -> Integer.valueOf(id)).collect(Collectors.toList());
        List<QuotaValue> quotaValues = this.getQuotaValues(quotaIds, dimensionIds, limit);
        if (null != quotaValues && quotaValues.size() > 0) {
            Map<Integer, QuotaDimension> dimensionNameMap = this.getDimensionNameMap(quotaValues);
            for (QuotaValue quotaValue : quotaValues) {
                List<String> dimIds = Arrays.asList(quotaValue.getDimensions().split(",")).stream().filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toList());
                StringBuilder builder = new StringBuilder();
                builder.append("|");
                for (String dimId : dimIds) {
                    QuotaDimension dimension = dimensionNameMap.get(Integer.valueOf(dimId));
                    builder.append(dimension.getDimensionName()).append("|");
                }
                Map<String, String> map = new LinkedHashMap<>();
                map.put("name" , builder.toString());
                map.put("value" , this.getValue(type, quotaValue));
                maps.add(map);
            }
        }
        return JSON.toJSONString(maps);
    }

    @Override
    public String getBarChartsJson(Map<String, String> param, List<Integer> dimensionIds, String type, Integer limit) {

        Map<String, List<String>> resultMap = new LinkedHashMap<>();
        /** 指标id集合 */
        List<Integer> quotaIds = param.keySet().stream().map(qId -> Integer.parseInt(qId)).collect(Collectors.toList());
        /** 待处理数据 */
        List<QuotaValue> quotaValues = this.getQuotaValues(quotaIds, dimensionIds, limit);
        if (quotaValues != null && quotaValues.size() > 0) {
            Map<Integer, QuotaDimension> dimensionNameMap = this.getDimensionNameMap(quotaValues);
            Set<String> collect = quotaValues.stream().map(item -> item.getDimensions()).collect(Collectors.toSet());
            List<String> dimensions = new ArrayList<>(collect);
            List<String> dimensionNames = new ArrayList<>();
            for (String dimension : dimensions) {
                List<String> ids = Arrays.stream(dimension.split(",")).filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toList());
                StringBuilder builder = new StringBuilder().append("|");
                for (String id : ids) {
                    QuotaDimension quotaDimension = dimensionNameMap.get(Integer.valueOf(id));
                    builder.append(quotaDimension.getDimensionName()).append("|");
                }
                dimensionNames.add(builder.toString());
            }
            resultMap.put("xAxis" , dimensionNames);
            Map<Integer, List<QuotaValue>> quotaMap = quotaValues.stream().collect(Collectors.groupingBy(key -> key.getQuotaId()));
            quotaMap.forEach((k, v) -> {
                String[] arr = new String[dimensions.size()];
                Arrays.fill(arr, "0");
                for (QuotaValue value : v) {
                    int index = dimensions.indexOf(value.getDimensions());
                    arr[index] = this.getValue(type, value);
                }
                List<String> list = new ArrayList<>(Arrays.asList(arr));
                resultMap.put(k.toString(), list);
            });
        }
        return JSON.toJSONString(resultMap);
    }

    @Override
    public PageUtil selectList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.get("pageNum");
        params.put("pageNum" , pageNum + "");
        Integer pageSize = (Integer) params.get("pageSize");
        params.put("pageSize" , pageSize + "");

        Integer quotaId = (Integer) params.get("quotaId");
        String dimIds = JSON.toJSONString(params.get("dimIds"));
        QueryWrapper<QuotaValue> wrapper = new QueryWrapper<>();
        wrapper.eq("QUOTA_ID" , quotaId);
        //封装维度筛选条件 大概执行sql如下
        //select * from quota_value where QUOTA_ID=quotaId AND (DIMENSIONS like “1” OR ...) AND(DIMENSIONS like "2" OR ...) AND...
        //添加指标id和DIMENSIONS字段的复合索引 CREATE INDEX QUOTAID_DIMENSIONS_INDEX ON QUOTA_VALUE('QUOTA_ID','DIMENSIONS') TABLESPACE JHK_QH;
        if (StringUtils.isNotBlank(dimIds)) {
            List<QuotaValueVo> dim = JSONArray.parseArray(dimIds, QuotaValueVo.class);
            Map<Integer, List<QuotaValueVo>> dimGroup = dim.stream().collect(Collectors.groupingBy(key -> key.getRootId()));
            dimGroup.forEach((k, v) -> {
                wrapper.and((obj) -> {
                    for (QuotaValueVo valueVo : v) {
                        obj.or().like("DIMENSIONS" , valueVo.getDimId());
                    }
                });
            });
        }
        IPage<QuotaValue> page = this.baseMapper.selectPage(new Query<QuotaValue>().getPage(params), wrapper);
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            //截取出所有的维度id 去重 一次查询出所有最后组装  这里的维度处理可以封装为一个方法 之后优化查询报表等接口可用
            String ids = page.getRecords().stream().map(QuotaValue::getDimensions).collect(Collectors.joining(","));
            Set<String> dimIdSet = Arrays.asList(ids.split(",")).stream().filter(id -> StringUtils.isNotBlank(id)).collect(Collectors.toSet());
            Map<Integer, QuotaDimension> dimensionMap = quotaDimensionMapper.selectBatchIds(dimIdSet).stream().collect(Collectors.toMap(QuotaDimension::getId, a -> a, (k1, k2) -> k1));
            for (QuotaValue value : page.getRecords()) {
                StringBuilder builder = new StringBuilder().append("|");
                String[] dimensionIds = value.getDimensions().split(",");
                for (String dimensionId : dimensionIds) {
                    if (StringUtils.isNotBlank(dimensionId)) {
                        QuotaDimension dimension = dimensionMap.get(Integer.valueOf(dimensionId));
                        builder.append(dimension.getDimensionName()).append("|");
                    }
                }
                value.setDimensionNames(builder.toString());
            }
        }
        return new PageUtil(page);
    }


}
